import React, { useState, forwardRef, useRef, useImperativeHandle } from 'react';
import { Form, Input, Modal, Button, Upload, message as Message, Select } from 'antd';

import { http_user_add, http_user_edit } from '@/api/systemManagement/user';
import { http_user_upload } from '@/api/system/user';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { validateMobile } from '@/utils/validate';
import { baseURL } from '@/utils/request';

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    Message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    Message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const selectOptions = [
  { value: 0, label: '超级管理员' },
  { value: 1, label: '管理员' },
  { value: 2, label: '普通用户' }
];

const UserFormDialog = forwardRef((props: any, ref) => {
  useImperativeHandle(ref, () => ({ showModal }));

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [type, setType] = useState<string>('');
  const [column, setColumn] = useState<any>({});
  const formRef = useRef<any>(null);

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>('');

  const canSelectOptions = selectOptions.filter(
    (it) => it.value > (sessionStorage.getItem('roleType') ? Number(sessionStorage.getItem('roleType')) : 2)
  );

  // 展示弹窗
  const showModal = async (type: string, record: any) => {
    setType(type);
    setColumn(record);
    await setIsModalOpen(true);
    if (type === 'edit') {
      setImageUrl(record.avatarUrl);
      formRef.current.setFieldsValue({
        nickname: record.nickname,
        phone: record.phone,
        roleType: record.roleType,
        password: record.password
      });
    }
  };

  const customRequest = ({ file }: { file: any }) => {
    const fd = new FormData();
    fd.append('file', file);
    http_user_upload(fd).then((res) => {
      setImageUrl(res.data.url);
    });
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  // 提交表单项
  const handleOk = async () => {
    const params = form.getFieldsValue();
    params.avatarUrl = imageUrl;
    try {
      if (type === 'add') {
        await http_user_add(params);
      } else {
        await http_user_edit({ ...params, userId: column.userId });
      }
      props.onGetUserList();
      form.resetFields();
      setIsModalOpen(false);
    } catch (error) {}
  };
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    setIsModalOpen(false);
  };

  return (
    <Modal
      className="base-dialog"
      title={type === 'add' ? '新增用户' : '编辑用户'}
      open={isModalOpen}
      onOk={handleOk}
      onCancel={handleCancel}
      footer={[
        <Button key="submit" type="primary" size={'middle'} onClick={handleOk}>
          确定
        </Button>,
        <Button key="back" size={'middle'} onClick={handleCancel}>
          取消
        </Button>
      ]}
    >
      <Form ref={formRef} form={form} labelCol={{ span: 4 }}>
        <Form.Item label="昵称" name="nickname" rules={[{ required: true, message: '请输入昵称' }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="手机"
          name="phone"
          rules={[
            { required: true, message: '请输入手机号' },
            { max: 11, message: '手机长度不合格!' },
            {
              pattern: new RegExp(validateMobile.rule(), 'g'),
              message: '请输入正确格式的手机号码!'
            }
          ]}
        >
          <Input disabled={type === 'edit'} />
        </Form.Item>
        <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
          <Input />
        </Form.Item>
        {column?.phone !== sessionStorage.getItem('phone') ? (
          <Form.Item label="权限" name="roleType" rules={[{ required: true, message: '请选择身份权限' }]}>
            <Select options={canSelectOptions} />
          </Form.Item>
        ) : null}
        <Form.Item label="头像">
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={beforeUpload}
            customRequest={customRequest}
          >
            {imageUrl ? <img src={baseURL + imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
});

export default UserFormDialog;
